import java.util.Objects;

public class HashBuck2<K,V> {
    public static final double DEFAULT_LOAD_FACTOR = 0.75;
    // 节点
    static class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int usedSize;

    public void put(K key,V val){
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        Node<K,V> prev = null;
        while (cur != null){
            if (cur.key.equals(key)){
                cur.val = val;
                return;
            }
            prev = cur;
            cur = cur.next;
        }
        Node<K,V> next = new Node<>(key,val);
        if (prev == null){
            array[index] = next;
        }else{
            prev.next = next;
        }
        usedSize++;
        // 插入元素成功后，检查当前散列表的负载因子
        if (loadFactor() >= DEFAULT_LOAD_FACTOR){
            // 负载因子大于等于规定的，就需要扩容
            array = resize();
        }
    }
    // 当负载因子大了，就扩容
    // 如果扩容了，则 每个元素应该重新 hash到哈希表中
    public Node<K,V>[] resize(){
        Node<K,V>[] newArray = (Node<K,V>[])new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node<K,V> cur = array[i];
            while (cur != null){
                int index = cur.key.hashCode() % array.length;
                // 保存cur后面的节点，防止被丢掉
                Node<K,V> curNext = cur.next;
                // 把 cur节点插入到新数组对应下标 -- 头插法
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        return newArray;
    }
    // 求负载因子
    public double loadFactor(){
        return 1.0*usedSize/array.length;
    }
    // 获取元素
    public V get(K key){
        int index = key.hashCode() % array.length;
        Node<K,V> cur = array[index];
        while (cur != null){
            if (cur.key.equals(key)){
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}

class Person{
    String id;
    public Person(String id) {
        this.id = id;
    }
    // equals和 hashCode要一起重写
    @Override
    // equals确定是否一样
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id);
    }
    @Override
    // hashCode确定位置
    public int hashCode() {
        return Objects.hash(id);
    }
}